import router from '@/router/index'
import store from '@/store/index'

const whiteList = ['/login', '/404']
router.beforeEach(async(to, from, next) => {
  if (store.getters.token) {
    // 1.登录之后掉接口
    // 2.刷新页面触发
    // 3.判断是否请求过用户信息
    // 4.{} =true 所以要没有userId 才发请求
    if (!store.getters.userInfo.userId) {
      const res = await store.dispatch('user/getUserInfo')
      //   console.log(res)
      const newRoutes = await store.dispatch('permission/filterRoutes', res.roles.menus)
      router.addRoutes([...newRoutes, { path: '*', redirect: '/404', hidden: true }])
      next(to.path)
    }

    if (to.path === '/login') {
      next('/')
    } else {
      next()
    }
  } else {
    if (whiteList.includes(to.path)) {
      next()
    } else {
      next('/login')
    }
  }
})
